// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.excel.TemplateModelBuildEventListener;
import com.fowo.api.common.model.ImportRow;
import com.fowo.api.common.model.RException;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.common.util.SheetUtils;
import com.fowo.api.entity.MarkingFail;
import com.fowo.api.mapper.MarkingFailMapper;
import com.fowo.api.model.marking.fail.MarkingFailExcelPo;
import com.fowo.api.model.marking.fail.MarkingFailImportPo;
import com.fowo.api.model.marking.fail.MarkingFailItemVo;
import com.fowo.api.model.marking.fail.MarkingFailSearchParamPo;
import com.fowo.api.model.marking.fail.MarkingFailVo;
import com.fowo.api.service.MarkingFailService;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.sys.entity.SysImportTemplate;
import com.fowo.api.sys.service.FileService;
import com.fowo.api.sys.service.SysImportTemplateService;
import com.fowo.api.user.model.JwtUserInfo;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 标发失败 服务实现类
 */
@Service
@Slf4j
@DS("ds24")
public class MarkingFailServiceImpl
  extends ServiceImpl<MarkingFailMapper, MarkingFail>
  implements MarkingFailService {

  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>();
  // 导出时单次查询最大记录数
  protected static final int EXPORT_QUERY_MAX_SIZE = 1000;
  // 支持导出的最大记录数(1048576 为 Excel 支持的最大行数)
  protected static final long EXPORT_MAX_SIZE = 1048575;

  @Resource
  protected FileService fileService;

  @Resource
  protected SysImportTemplateService importTemplateService;

  @Resource
  protected Validator validator;

  /**
   * 创建标发失败
   * @param model 标发失败
   * @return 新数据的主键
   */
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(MarkingFailVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    MarkingFail entity = new MarkingFail();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.save(entity)) {
      return entity.getId();
    }
    throw new Exception("标发失败保存失败");
  }

  /**
   * 更新标发失败
   * @param model 标发失败
   * @return 更新是否成功
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(MarkingFailVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    MarkingFail entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("标发失败不存在");
    }
    BeanUtils.copyProperties(
      model,
      entity,
      "id",
      "createTime",
      "createUser",
      "lastUpdateTime",
      "lastUpdateUser"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      return true;
    }
    return false;
  }/**
   * 更新标发失败（带空值）
   * @param model 标发失败
   * @return 更新是否成功
   */

  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(MarkingFailVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    MarkingFail entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("标发失败不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(MarkingFail::getLastUpdateTime, model.getLastUpdateTime())
      .set(MarkingFail::getLastUpdateUser, model.getLastUpdateUser())
      .set(MarkingFail::getPlatformNumber, model.getPlatformNumber())
      .set(MarkingFail::getShippingTimeLimit, model.getShippingTimeLimit())
      .set(
        MarkingFail::getSystemTrackingNumber,
        model.getSystemTrackingNumber()
      )
      .set(MarkingFail::getLocalStatus, model.getLocalStatus())
      .set(MarkingFail::getProduct, model.getProduct())
      .set(MarkingFail::getPlatform, model.getPlatform())
      .set(MarkingFail::getLogisticsMethods, model.getLogisticsMethods())
      .set(MarkingFail::getCarriers, model.getCarriers())
      .set(MarkingFail::getDeliveryServices, model.getDeliveryServices())
      .set(MarkingFail::getTrackingNumber, model.getTrackingNumber())
      .set(MarkingFail::getOnlineStatus, model.getOnlineStatus())
      .set(MarkingFail::getMarkingStatus, model.getMarkingStatus())
      .set(MarkingFail::getDeliveriesNumber, model.getDeliveriesNumber())
      .set(MarkingFail::getMarkingTime, model.getMarkingTime())
      .eq(MarkingFail::getId, model.getId())
      .update();
    if (isOk) {}
    return isOk;
  }

  /**
   * 删除标发失败
   * @param id 标发失败的主键
   * @return 删除是否成功
   */
  @Override
  public boolean delete(Long id) throws Exception {
    return this.removeById(id);
  }

  /**
   * 批量删除标发失败
   * @param ids 标发失败的主键列表
   * @return 删除是否成功
   */
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    return baseMapper.deleteBatchIds(ids) > 0;
  }

  /**
   * 导入单行处理
   * @param row 要导入的行
   * @param rowNumber 所在行号
   * @param vo 输出VO,可空
   * @param variables 变量池，用于在一次导入过程中保存临时信息
   * @return 导入行对象
   */
  protected ImportRow<MarkingFailImportPo> excelToImportRow(
    MarkingFailImportPo row,
    Integer rowNumber,
    MarkingFailVo vo,
    Map<String, Object> variables
  ) {
    ImportRow<MarkingFailImportPo> ir = new ImportRow<MarkingFailImportPo>();
    ir.setRowNumber(rowNumber);
    ir.setRow(row);
    if (SheetUtils.isAllFieldsEmpty(row)) {
      ir.setEmptyRow(true);
      ir.addError("", "空行");
      return ir;
    }
    final Set<ConstraintViolation<MarkingFailImportPo>> validate = validator.validate(
      row
    );
    boolean isOutputVo = vo != null;
    if (!isOutputVo) {
      vo = new MarkingFailVo();
    }
    BeanUtils.copyProperties(row, vo);
    // 收集基本校验错误
    ir.initErrors(validate, MarkingFailImportPo.class);

    // 一般数据处理
    vo.setShippingTimeLimit(
      SheetUtils.tryToDateTime(row.getShippingTimeLimit())
    );
    vo.setLocalStatus(SheetUtils.tryToBoolean(row.getLocalStatus()));
    vo.setOnlineStatus(SheetUtils.tryToBoolean(row.getOnlineStatus()));
    vo.setMarkingStatus(SheetUtils.tryToBoolean(row.getMarkingStatus()));
    vo.setDeliveriesNumber(SheetUtils.tryToInteger(row.getDeliveriesNumber()));
    vo.setMarkingTime(SheetUtils.tryToDateTime(row.getMarkingTime()));

    return ir;
  }

  /**
   * 导入预览
   * @param sysFile 已上传到系统的文件
   */
  @Override
  public List<ImportRow<MarkingFailImportPo>> importPreview(
    SysFile sysFile,
    Long templateId
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    Map<String, Object> variables = new HashMap<>();
    try (InputStream in = fileService.read(sysFile)) {
      List<ImportRow<MarkingFailImportPo>> rows = new ArrayList<>();

      // 读取 Excel 到 rows
      EasyExcel
        .read(in)
        .useDefaultListener(false)
        .registerReadListener(
          new TemplateModelBuildEventListener<>(
            MarkingFailImportPo.class,
            importTemplate
          ) {
            @Override
            public void invokeRow(
              MarkingFailImportPo row,
              AnalysisContext cxt
            ) {
              ImportRow<MarkingFailImportPo> ir = excelToImportRow(
                row,
                cxt.readRowHolder().getRowIndex(),
                null,
                variables
              );
              if (ir.isEmptyRow()) {
                return;
              }
              rows.add(ir);
            }
          }
        )
        .sheet()
        .doRead();

      return rows;
    }
  }

  /**
   * 完成导入
   * @param rows 预导入的行信息
   */
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void importDone(List<ImportRow<MarkingFailImportPo>> rows)
    throws Exception {
    Map<String, Object> variables = new HashMap<>();
    for (int i = 0; i < rows.size(); i++) {
      ImportRow<MarkingFailImportPo> row = rows.get(i);
      MarkingFailVo vo = new MarkingFailVo();
      row = excelToImportRow(row.getRow(), row.getRowNumber(), vo, variables);
      if (row.getErrors() != null && row.getErrors().size() > 0) {
        throw new RException(
          String.format(
            "第%d行（Excel第%d行）数据验证错误：%s",
            i + 1,
            row.getRowNumber(),
            row.getJoinErrorMessage()
          )
        );
      }
      create(vo);
    }
  }

  /**
   * 导出
   * @param search 查询条件
   */
  @Override
  public void export(
    MarkingFailSearchParamPo search,
    HttpServletResponse response
  ) throws Exception {
    search.setPageSize(EXPORT_QUERY_MAX_SIZE);
    int current = 1;
    List<MarkingFailExcelPo> items = new ArrayList<MarkingFailExcelPo>();
    while (true) {
      search.setCurrent(current);
      Page<MarkingFailItemVo> page = this.pageSearch(search);
      if (page.getTotal() > EXPORT_MAX_SIZE) {
        throw new RException("导出记录数超出限制！");
      }
      List<MarkingFailItemVo> list = page.getRecords();
      if (list.isEmpty()) {
        break;
      }
      for (MarkingFailItemVo item : list) {
        MarkingFailExcelPo excel = new MarkingFailExcelPo();
        BeanUtils.copyProperties(item, excel);
        if (item.getLocalStatus() != null) {
          excel.setLocalStatus(item.getLocalStatus() ? "是" : "否");
        }
        if (item.getOnlineStatus() != null) {
          excel.setOnlineStatus(item.getOnlineStatus() ? "是" : "否");
        }
        if (item.getMarkingStatus() != null) {
          excel.setMarkingStatus(item.getMarkingStatus() ? "是" : "否");
        }

        items.add(excel);
      }
      if (list.size() < EXPORT_QUERY_MAX_SIZE) {
        break;
      }
      current++;
    }

    ResponseUtils.setAttachmentFileName(response, "标发失败.xlsx");
    EasyExcel
      .write(response.getOutputStream())
      .sheet()
      .head(MarkingFailExcelPo.class)
      .doWrite(items);
  }

  /**
   * 通过平台单号查询标发失败主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdByPlatformNumber(String platformNumber) {
    return this.baseMapper.getIdByPlatformNumber(platformNumber);
  }

  /**
   * 通过平台单号查询标发失败多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsByPlatformNumber(List<String> list) {
    return this.baseMapper.getIdsByPlatformNumber(list);
  }

  /**
   * 通过标发失败主键查询平台单号
   */
  @Override
  public String getPlatformNumberById(Long id) {
    return this.baseMapper.getPlatformNumberById(id);
  }

  /**
   * 通过标发失败主键查询平台单号列表
   */
  @Override
  public List<String> getPlatformNumberByIds(List<Long> ids) {
    return this.baseMapper.getPlatformNumberByIds(ids);
  }

  /**
   * 获取详情
   * @param id 标发失败的主键
   */
  @Override
  public MarkingFailVo getVoById(Long id) throws Exception {
    MarkingFailVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }
    return vo;
  }

  /**
   * 分页查询标发失败
   * @param search 查询条件
   * @return 标发失败分页查询结果
   */
  @Override
  public Page<MarkingFailItemVo> pageSearch(MarkingFailSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    Page<MarkingFailItemVo> page =
      this.baseMapper.pageSearch(search.toPage(), search);
    return page;
  }

  /**
   * 列表查询标发失败
   * @param search 查询条件
   * @return 标发失败列表查询结果
   */
  @Override
  public List<MarkingFailItemVo> search(MarkingFailSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询标发失败最后更新时间
   * @param search 查询条件
   * @return 标发失败最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(MarkingFailSearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }
}
